package cn.dkdoo.utils.templateCommon;

import cn.dkdoo.utils.config.exception.DkdTransactionException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.data.annotation.Id;

import java.lang.reflect.Field;

/**
 * @author nicky
 * @date 2021/7/7 上午10:07
 */
public abstract class DkdTemplate<T> implements InitializingBean {
    protected Class<T> beanClass;
    protected Field idField;
    protected String collectionName;

    public DkdTemplate() {
    }

    public abstract Class<T> initBeanClass();

    public abstract String initCollectionName();

    @Override
    public void afterPropertiesSet() throws Exception {
        this.beanClass = initBeanClass();
        for (Field declaredField : this.beanClass.getDeclaredFields()) {
            if (declaredField.getAnnotation(Id.class) != null || declaredField.getName().equals("id")) {
                declaredField.setAccessible(true);
                this.idField = declaredField;
                break;
            }
        }
        if (idField == null) {
            throw new DkdTransactionException("未找到成员属性：id");
        }
        this.collectionName = initCollectionName();
    }
}
